  
//
//  CJBaseRequest.m
//  DatangLife
//
//  Created by 娜 on 2018/4/19.
//  Copyright © 2018年 DatangLife. All rights reserved.
//

#import "CJBaseRequest.h"
#import "CJRequestManager.h"
@implementation CJBaseRequest
#pragma mark - 构造
+ (instancetype)cj_request {
    return [[self alloc] init];
}

+ (instancetype)cj_requestWithUrl:(NSString *)cj_url {
    return [self cj_requestWithUrl:cj_url isPost:NO withParameters:nil];
}

+ (instancetype)cj_requestWithUrl:(NSString *)cj_url isPost:(BOOL)cj_isPost {
    return [self cj_requestWithUrl:cj_url isPost:cj_isPost withParameters:nil];
}

+ (instancetype)cj_requestWithUrl:(NSString *)cj_url isPost:(BOOL)cj_isPost withParameters:(NSDictionary *)cj_parameters{
    CJBaseRequest *request = [self cj_request];
    request.cj_url = cj_url;
    request.cj_isPost = cj_isPost;
    request.cj_parameters = cj_parameters;
    NSLog(@"%@",cj_url);
    
     NSLog(@"%@",cj_parameters);
    return request;
}


#pragma mark - 发送请求


- (void)cj_sendRequestWithCompletion:(CJAPIDicCompletion)completion {
    
    // 链接
    NSString *urlStr = self.cj_url;
    if (urlStr.length == 0) return ;
    
    // 参数
    NSDictionary *params = [NSDictionary dictionary];
    if (self.cj_parameters.allKeys.count == 0) {
        params = nil;
    }else{
        params = self.cj_parameters;
    }
    
    NSLog(@"%@",self.cj_parameters);
    
    // 普通POST请求
    if (self.cj_isPost) {
        if (self.cj_imageArray.count == 0) {
            // 开始请求
            [CJRequestManager POST:urlStr parameters:params responseSeializerType:CJResponseSeializerTypeData success:^(id responseObject) {
                NSLog(@"%@",responseObject);
                // 处理数据
                [self handleResponse:responseObject completion:completion];
            } failure:^(NSError *error) {
                // 数据请求失败，暂时不做处理
                [NSNotificationCenter postNotification:kCJRequestErroNotification];
                NSLog(@"%ld",error.code);
                if (error.code == -1011) {
                    [CJUIKit showErrorWithStatus:@"服务器超时"];
                }
            }];
        }
        
    } else { // 普通GET请求
        // 开始请求
        [CJRequestManager GET:urlStr parameters:params responseSeializerType:CJResponseSeializerTypeData success:^(id responseObject) {
            
            
            // 处理数据
            [self handleResponse:responseObject completion:completion];
        } failure:^(NSError *error) {
            // 数据请求失败，暂时不做处理
            if (error.code == -1011) {
                [CJUIKit showErrorWithStatus:@"服务器超时"];
            }
            [NSNotificationCenter postNotification:kCJRequestErroNotification];
        }];
    }
    
    // 上传图片
    if (self.cj_imageArray.count) {
        [CJRequestManager POST:[urlStr noWhiteSpaceString] parameters:params responseSeializerType:CJResponseSeializerTypeData constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

            
            
            for (NSInteger index = 0; index < self.cj_imageArray.count; index ++) {
                NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
                formatter.dateFormat=@"yyyyMMddHHmmsss";
                NSString *str=[formatter stringFromDate:[NSDate date]];
                NSString *fileName=[NSString stringWithFormat:@"%@%ld.jpg",str,index];

                [formData appendPartWithFileData:self.cj_imageArray[index] name:@"Photo" fileName:fileName mimeType:@"image/jpeg"];
            }
        } success:^(id responseObject) {
            // 处理数据
            [self handleResponse:responseObject completion:completion];
        } failure:^(NSError *error) {
            if (error.code == -1011) {
                [CJUIKit showErrorWithStatus:@"服务器超时"];
            }
            // 请求成功，发布通知
            [NSNotificationCenter postNotification:kCJRequestErroNotification];
            // 数据请求失败，暂时不做处理
            
        }];
    }
}



- (void)handleResponse:(id)responseObject completion:(CJAPIDicCompletion)completion {
    
    
    NSLog(@"%@",responseObject);
    // 接口约定，如果message为retry即重试
//    if ([responseObject[@"code"] isEqualToString:@"retry"]) {
//        [self cj_sendRequestWithCompletion:completion];
//        return  ;
//    }
    
    // 数据请求成功回调
    BOOL success = [responseObject[@"code"] integerValue] == 200 ? YES :NO;
    // 请求成功，发布通知
    [NSNotificationCenter postNotification:kCJRequestSuccessNotification];
    if (completion) {
        completion(responseObject[@"Rows"], success, responseObject[@"msg"]);
    }
//    else if (self.cj_delegate) {
//        if ([self.cj_delegate respondsToSelector:@selector(requestSuccessReponse:response:message:)]) {
//            [self.cj_delegate requestSuccessReponse:success response:responseObject[@"data"] message:@""];
//        }
//    }

}

// 设置链接
- (void)setCj_url:(NSString *)cj_url {
    if (cj_url.length == 0 || [cj_url isKindOfClass:[NSNull class]]) {
        return ;
    }
    _cj_url = cj_url;
}
@end
